import { PropsWithChildren, useState, useRef } from "react";
import { RightOutlined } from '@ant-design/icons';
import './index.less';

export enum TriggerPosition {
    // Top = 'top',
    // Bottom = 'bottom',
    Left = 'left',
    Right = 'right'
}

const CPositionMap = new Map<TriggerPosition, { className: string; rotate: number }>([
    // [TriggerPosition.Top, { className: 'expand-icon-top', rotate: 90 }],
    // [TriggerPosition.Bottom, { className: 'expand-icon-bottom', rotate: 270 }],
    [TriggerPosition.Left, { className: 'expand-icon-left', rotate: 0 }],
    [TriggerPosition.Right, { className: 'expand-icon-right', rotate: 0 }],
])

/**
 * 折叠面板
 * 动画效果必须设置初始width
 */
export function Collapse(props: PropsWithChildren<{
    /** 收起展开出现的位置 */
    triggerPosition: TriggerPosition,
    className?: string;
    /** 是否默认展开 */
    defaultExpand?: boolean;
}>) {
    const { children, className, triggerPosition, defaultExpand = true } = props;
    const [showTrigger, setShowTrigger] = useState<boolean>(defaultExpand === true ? false : true);
    const [expand, setExpand] = useState<boolean>(defaultExpand);

    const timer = useRef<number | null>(null);


    const getExpandIcon = () => {
        const { className, rotate } = CPositionMap.get(triggerPosition)!;
        const r = expand ? rotate : 180 - rotate;
        return <div className={`expand-icon ${className}`} onClick={() => setExpand((prev) => !prev)} >
            <RightOutlined rotate={r} />
        </div>
    }

    const handleMouseEnter = () => {
        if (timer.current) {
            clearTimeout(timer.current);
        }
        setShowTrigger(true)
    }

    const handleMouseLeave = () => {
        if (timer.current) {
            clearTimeout(timer.current);
        }
        timer.current = (setTimeout(() => {
            if (expand) {
                setShowTrigger(false);
            }
            timer.current = null;
        }, 2000) as unknown as number);
    }

    return <div className={`collapse-main ${expand ? '' : 'width0'} ${className}`} onMouseEnter={handleMouseEnter} onMouseLeave={handleMouseLeave}>
        {showTrigger && getExpandIcon()}
        {children}
    </ div>
}